<?php

class Assessments extends CI_Model {

	function __construct() {
    	parent::__construct();
    }
     
    /**
     * Create an assessment item
     * @param array data - [title,due_date,weight]
     * @return  bool
     */
     
   public function create_assessment($data) {
   	
   		//ensure an assessment with this title does not exist
		/*if(_check_assessment_exists($data['assessment_title'])){
			$this->session->set_flashdata('errors', 'Error: This assessment item exists.' );
        	return FALSE;
			}
		else
			{*/
			if ( $this->db->insert('assessments', $data) ) {
        	//$this->session->set_flashdata('notices', 'Assessment added successfully.' );
   			return TRUE;
   			/*}*/
	
  		 }
   }
   
    /**
     * Change an assessment item
     * @param int assessment_id
     * @param array data
     * @return  bool
     */
     
   public function change_assessment($assessment_id, $data) {
		$this->db->where('assessment_id', $assessment_id);
		if ( $this->db->update('assessments', $data) ){
		//$this->session->set_flashdata('notices', 'Assessment updated successfully.' );
		return TRUE;
		}else{
		return FALSE;
		}
   }
   
    /**
     * Delete an assessment item
     * @param int assessment_id
     * @return  bool
     */
     
   public function delete_assessment($assessment_id) {
		if ( $this->db->delete('assessments', array('assessment_id' => $assessment_id))  ){
		//$this->session->set_flashdata('notices', 'Assessment deleted successfully.' );
		return TRUE;
		}else{
		return FALSE;
		}
   }
   
    /**
     * Return assessment items by due date for students
     * @param int user_id
     * @return  array
     */
     
   public function get_assessment_items($user_id) {
		$query = $this->db->query('SELECT A.assessment_id,  A.assessment_title, A.due_date, A.weight, S.marked, S.result FROM (SELECT assessment_id, assessment_title, due_date, weight FROM assessments ORDER BY due_date ASC) AS A LEFT JOIN (SELECT assessment_id, marked, result FROM submissions WHERE user_id = '.$user_id.') AS S ON S.assessment_id = A.assessment_id GROUP BY A.assessment_id ORDER BY due_date ASC, assessment_id ASC;');
		if ($query->num_rows() > 0) {
      $result = $query->result_array();
       return $result;
    } else {
      return false;
    }
    
   }

    /**
     * Get all assessment items
     * @return  array
     */
   public function get_all_assessment_items() {
    $this->db->select('*');
    $this->db->from('assessments');
    $query = $this->db->get();
    $result = $query->result_array();
    return $result;
   }  
   
    /**
     * Return all future assessment items by due date
     * for Tutors, Lecturers and Admins
     * @return  array
     */
     
   public function get_future_items() {
		$query = $this->db->query('SELECT assessment_id, assessment_title, due_date FROM assessments WHERE due_date > NOW() ORDER BY due_date ASC');
		$result = $query->result_array();
		return $result;
   }
   
   
    /**
     * Return all past assessment items by due date
     * for Tutors, Lecturers and Admins
     * @return  array
     */
     
   public function get_past_items() {
		$query = $this->db->query('SELECT assessment_id, assessment_title, due_date FROM assessments WHERE due_date <= NOW() ORDER BY due_date DESC');
		$result = $query->result_array();
		return $result;
   }
   
    /**
     * Return all assessment items still due by date
     * for Students
     * @param int user_id
     * @return  array
     */
     
   public function get_due_items($user_id) {
		$query = $this->db->query('SELECT assessment_id, assessment_title, due_date, (SELECT timestamp FROM submissions WHERE assessment_id = A1.assessment_id AND user_id = '.$user_id.') AS submitted FROM assessments AS A1 WHERE due_date > NOW() ORDER BY due_date ASC;');
		$result = $query->result_array();
		return $result;
   }
   
    /**
     * Return all assessment items due in the past
     * for Students
     * @param int user_id
     * @return  array
     */
     
   public function get_pastd_items($user_id) {
		$query = $this->db->query('SELECT A.assessment_id,  A.assessment_title, A.due_date, S.marked, S.result FROM (SELECT assessment_id, assessment_title, due_date FROM assessments WHERE due_date <= NOW() ORDER BY due_date ASC) AS A LEFT JOIN (SELECT assessment_id, marked, result FROM submissions WHERE user_id = '.$user_id.') AS S ON S.assessment_id = A.assessment_id GROUP BY A.assessment_id;');
		$result = $query->result_array();
		return $result;
   }
   
    /**
     * Return details of assessment item
     * @param int assessment_id
     * @return  array
     */
     
   public function get_assessment_details($assessment_id) {
  	$query = $this->db->query('SELECT * FROM assessments WHERE assessment_id = '.$assessment_id);
	$result = $query->row_array();
	return $result;
   }
      
    /**
     * Check whether the assessment is within its due date
     * @param int assessment_id
     * @return  bool
     */
     
   public function is_within_date($assessment_id) {
		$this->db->select('due_date');
        $this->db->from('assessments');
        $this->db->where('assessment_id', $assessment_id);
		$query = $this->db->get();
		$row = $query->row();
		$current_time = time();
		echo $row->body;
		
		
		//No assessment with assessment id
		if ( $query->num_rows() > 0 )
		{
		return False;
		}
		//If the assessment has a due date greater than the current time
		if( $row->due_date > $current_time){
		return True;
		}
		else{
		return False;
		}
   }
   
    /**
     * Check whether the assessment has been submitted
     * @param int assessment_id
     * @param int user_id
     * @return  bool
     */
     
   public function is_assessment_submitted($assessment_id, $user_id) {
		$this->db->select('submission_id,timestamp,marked,result');
		$this->db->from('submissions');
		$this->db->where('assessment_id', $assessment_id);
		$this->db->where('user_id', $user_id);
		
		$query = $this->db->get();
		
		if ($query->num_rows() > 0) {
			$result = $query->result_array();
			return $result;
		} else {
			return false;
		}
   }
   
    /**
     * Check whether the group assessment has been submitted
     * @param int assessment_id
     * @param int group_id
     * @return  bool
     */
     
   public function is_group_assessment_submitted($assessment_id, $group_id) {
		$this->db->select('submission_id');
		$this->db->from('submissions');
		$this->db->where('assessment_id', $assessment_id);
		$this->db->where('group_id', $group_id);
		
		$query = $this->db->get();
		
		if ($query->num_rows() > 0) {
			return true;
		} else {
			return false;
		}
   }
   
    /**
     * Set grade result for assessment item
     * @param int submission_id
     * @param int grade
     * @return  bool
     */
     
   public function set_assessment_result($submission_id, $grade) {
		if($this->db->query('UPDATE submissions SET result='.$grade.', marked=1 WHERE submission_id='.$submission_id.';')){
	   		return true;
	   	}else{
	   		return false;
	   	}
   }
   
    /**
     * Submit assessment item
     * @param int assessment_id
     * @param int user_id
     * @param string assessment_file
     * @return  bool
     */
     
   public function submit_assessment($assessment_id, $user_id, $assessment_file=NULL) {
   //currently the file is not inserted into the database, nor is group set
   
   	if($this->db->query('INSERT INTO submissions (user_id, group_id, assessment_id) VALUES ('.$user_id.', 0, '.$assessment_id.');')){
   		return true;
   	}else{
   		return false;
   	}
	
   }
   
    /**
     * Return assessment item
     * @param int assessment_id
     * @param int user_id
     * @return  array
     */
     
   public function get_assessment($assessment_id, $user_id) {
	
   }
   
    /**
     * Return all submissions of an assessment item
     * @param int assessment_id
     * @return  array
     */
     
   public function get_submissions($assessment_id) {
		
		$query = $this->db->query('SELECT CONCAT(first_name, \' \', last_name) AS user_name, submissions.user_id, submission_id, marked, timestamp  FROM submissions LEFT JOIN users ON submissions.user_id = users.user_id WHERE assessment_id = '.$assessment_id.' ORDER BY timestamp DESC;');
		
		
		if ($query->num_rows() > 0) {
			$result = $query->result_array();
			return $result;
		} else {
			return false;
		}
   
   	
   }
   
    /**
     * Get group name
     * @param int user_id
     * @return  string
     */
     
   public function get_group_name($user_id) {
		
		$query = $this->db->query('SELECT group_name FROM groups AS G RIGHT JOIN group_members AS M ON G.group_id = M.group_id WHERE M.user_id = '.$user_id.' LIMIT 1;');
		
		
		if ($query->num_rows() > 0) {
			$result = $query->result_array();
			$result = $result[0]['group_name'];
			return $result;
		} else {
			return false;
		}
   
   	
   }
   
    /**
     * Get total weight of assessments
     * @return  string
     */
     
   public function get_total_weight() {
		
		$query = $this->db->query('SELECT SUM(weight) AS total_weight FROM assessments;');
		
		
		if ($query->num_rows() > 0) {
			$result = $query->result_array();
			$result = $result[0]['total_weight'];
			return $result;
		} else {
			return false;
		}
   
   	
   }
   
    /**
     * Check assessment item exists
     * @param string assessment_title
     * @return  bool
     */
   
   public function _check_assessment_exists($assessment_title){
   		$this->db->select('assessment_title');
        $this->db->from('assessments');
        $this->db->where('assessment_title', $assessment_title);
        $query = $this->db->get();

        // Return true if any results found
        if ($query->num_rows() > 0) { return TRUE;}
        else {return FALSE;}

   }
   
    /**
     * Check whether peer review has been submitted
     * @param int user_id
     * @param int week_no
     * @return  bool
     */
   
   public function _check_peer_review($user_id,$week_no){
   		$query = $this->db->query('SELECT * FROM peer_reviews WHERE sender_id = '.$user_id.' AND week_no = '.$week_no.';');

        // Return true if any results found
        if ($query->num_rows() > 0) { return TRUE;}
        else {return FALSE;}
   }


   /**
    * Add a peer review like a boss
    */
   public function add_peer_review($data) {
    if( $this->db->insert('peer_reviews', $data) ) {
      return true;
    } else {
      return false;
    }
   }


   /**
    * Check if a peer review has been submitted already
    */
   public function check_peer_review_exists($sender_id, $receiver_id, $assessment_id, $week_no) {
      $this->db->select('*');
      $this->db->where('sender_id', $sender_id);
      $this->db->where('receiver_id', $receiver_id);
      $this->db->where('assessment_id', $assessment_id);
      $this->db->where('week_no', $week_no);
      $query = $this->db->get('peer_reviews');
      if ($query->num_rows() > 0) {
        return true;
      }
      return false;
   }



   /**
    * Get peer reviews
    */
   public function get_peer_reviews($student_id = false, $assessment_id = false, $week_no = false, $group_id = false) {
      $this->db->select('first_name, last_name, assessment_title, p.week_no, p.result, group_name', false);
      $this->db->from('peer_reviews p');
      $this->db->join('assessments', 'assessments.assessment_id = p.assessment_id');
      $this->db->join('users', 'users.user_id = p.receiver_id');
      $this->db->join('groups', 'groups.group_id = p.group_id');
      if ($student_id && !empty($student_id)) {
        $this->db->where('user_id', $student_id);
      }
      if ($assessment_id && !empty($assessment_id)) {
        $this->db->where('p.assessment_id', $assessment_id);
      }
      if ($week_no && !empty($week_no)) {
        $this->db->where('p.week_no', $week_no);
      }
      if ($group_id && !empty($group_id)) {
        $this->db->where('p.group_id', $group_id);
      }
      $query = $this->db->get();
      $result = $query->result_array();
      return $result;
   }



   
    /**
     * Reformat date and combine it with time for assessment due date
     * @param string date
     * @param string time
     * @return  string
     */
   
   public function _format_due_date($date, $time){
		if(strlen($date)!= 10 || strlen($time) != 5){
		return FALSE;
		}else{
		date_default_timezone_set('Australia/Brisbane');
		$date=trim($date);//$date in 'dd/mm/yyyy' format
		list($d, $m, $y) = explode('/', $date);
		$mk=mktime(0, 0, 0, $m, $d, $y);
		$formatteddate=strftime('%Y-%m-%d',$mk);
		$combine = $formatteddate.' '.$time.':59';
		$fullyformatted = stripslashes($combine);
		return $fullyformatted;
		}

   }






   /**
    * Enter tutor feedback (review and grade)
    */
   public function add_feedback($data) {
    if ($this->db->insert('assessment_feedback', $data)) {
      return true;
    } else {
      return false;
    } 
   }

   /**
    * Get all feedback
    */
   public function get_all_feedback() {
    $this->db->select('*');
    $this->db->from('assessment_feedback');
    $this->db->join('assessments', 'assessments.assessment_id = assessment_feedback.assessment_id');
    $this->db->join('users', 'users.user_id = assessment_feedback.user_id');
    $query = $this->db->get();
    $result = $query->result_array();
    return $result;
   }


   /**
    * Check is feedback has been submitted already
    */
   public function check_feedback_exists($user_id, $assessment_id) {
    $this->db->select('*');
    $this->db->where('user_id', $user_id);
    $this->db->where('assessment_id', $assessment_id);
    $query = $this->db->get('assessment_feedback');
    if ($query->num_rows() > 0) {
      return true;
    }
    return false;
   }


   public function delete_feedback($review_id) {
      if ( $this->db->delete('assessment_feedback', array('review_id' => $review_id)) ) {
        return true;
      } else {
        return false;
      }
   }


}